package com.ly.gen.config;

import com.ly.gen.utils.FileUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.sqlite.SQLiteDataSource;

import javax.sql.DataSource;
import java.io.File;
import java.io.FileOutputStream;

/**
 * 数据源配置
 *
 * @author yuan.lei
 * @date 2023/2/7
 **/
@Configuration
public class DataSourceConfig {

    private static final String DB_FILE = "mpcg_data_conn.db";

    @Bean(name = "dataSource")
    public DataSource dataSource() {
        SQLiteDataSource dataSource = new SQLiteDataSource();
        try {
            ClassPathResource classPathResource = new ClassPathResource(DB_FILE);
//            File file = ResourceUtils.getFile("classpath:" + DB_FILE);
            File sqlFile = new File(FileUtils.getDataPath() + DB_FILE);
            if (!sqlFile.exists()) {
                IOUtils.copy(classPathResource.getInputStream(), new FileOutputStream(sqlFile));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(FileUtils.getDataPath() + DB_FILE);
        dataSource.setUrl("jdbc:sqlite:" + FileUtils.getDataPath() + DB_FILE);
        return dataSource;
    }

    @Bean
    public NamedParameterJdbcTemplate namedParameterJdbcTemplate(DataSource dataSource) {
        return new NamedParameterJdbcTemplate(dataSource);
    }

}
